package com.ywyself.plugin.spider.impl;

import com.sun.istack.internal.NotNull;
import com.ywyself.plugin.spider.Spider;
import com.ywyself.plugin.spider.uils.SendHttp;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.List;

/**
 * 读一读http://du1du.org
 */
@SuppressWarnings("unused")
public class Du1Du extends Spider {

    /**
     * 列出章节
     *
     * @param url 章节目录的地址
     * @return 所有章节的章节名称和链接地址，list中为{章节名称，链接地址}
     */
    @Override
    public List<String[]> listCate(@NotNull String url) {
        String html = SendHttp.get(url, "gbk");
        if (html == null || html.trim().length() == 0) {
            return null;
        }
        Document doc = Jsoup.parse(html);
        Elements chapterLinks = doc.getElementById("chapters-list").getElementsByTag("a");
        if (chapterLinks == null || chapterLinks.size() == 0) {
            return null;
        }
        java.util.List<String[]> list = new java.util.ArrayList<>(100);
        String[] info;
        for (Element e : chapterLinks) {
            info = new String[2];
            info[0] = e.text();
            info[1] = e.attr("href");
            list.add(info);
        }
        return list;
    }

    /**
     * 读取章节内容
     *
     * @param url 章节链接地址
     * @return {章节名称(text文本), 章节内容(html文本)}
     */
    @Override
    public String[] getContent(@NotNull String url) {
        String html = SendHttp.get(url, "gbk");
        if (html == null || html.trim().length() == 0) {
            return null;
        }
        Document doc = Jsoup.parse(html);
        String title = doc.getElementById("h1").select("h1").text();
        String content = doc.getElementById("txtContent").html();
        return new String[]{title, content};
    }
}
